package com.itzhigui.controller.api;

import com.itzhigui.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 发送短信的控制器
 *
 * @author java1412
 * @since 2023-11-10 14:52:54
 */
@RestController
@Slf4j
@RequestMapping(value = "/api/sms")
@Api(value = "发送短信", tags = "ApiSmsController")
public class ApiSmsController {
//    @Resource
//    private SmsUtil smsUtil;

    @Resource
    private VerifyCodeUtil verifyCodeUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 发送验证码
    @ApiOperation(value = "发送验证码", notes = "发送4位数字验证码")
    @GetMapping(value = "/sendVerifyCode")
    public ResponseUtil sendVerifyCode(String phone) {
        // 生成四位验证码
        String code = verifyCodeUtil.genFourDigitCode();
        // 向指定的手机号发送验证码,这里就注释，将来项目上线将这行代码放开
        // smsUtil.sendVerifyCode(phone, code);
        // 这里为了测试方便，所以在控制台打印手机号和验证码
        System.out.println(phone + " - " + code);
        // 发送完验证码后需要存到redis中，因为将来需要检验
        // 生成存redis的key
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // phone + "-" + code
        stringRedisTemplate.opsForValue().set(uuid, phone + "-" + code);
        // 给验证码设置有效期,5分钟
        stringRedisTemplate.expire(uuid, ConstantUtil.VERIFY_CODE_TIMEOUT, TimeUnit.MINUTES);
        // 向前端返回短信验证码发送成功状态
        Map<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        return ResponseUtil.get(ResponseEnum.SMS_VERIFY_4_CODE_SUCCESS, map);
    }
}
